package me.zhengjie.controller;

import lombok.RequiredArgsConstructor;
import me.zhengjie.domain.SseService;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@RestController
@RequiredArgsConstructor
public class SseController {

    private final SseService sseService;

    @GetMapping(value = "/unbinding", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    private SseEmitter connect(HttpServletResponse response){
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        response.addHeader("Content-Type","text/event-stream");
        response.addHeader("Cache-Control","no-cache");
        response.addHeader("X-Accel-Buffering","no");

        String ip = request.getRemoteAddr() + ":" + request.getRemotePort();
        SseEmitter sseEmitter = sseService.connect(ip);
        try {
            sseEmitter.send(SseEmitter.event().name("unbinding").comment("开始推送拆解作业信息："));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return sseEmitter;
    }

    @GetMapping(value = "/errorInfo", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    private SseEmitter connect2(HttpServletResponse response){
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        response.addHeader("Content-Type","text/event-stream");
        response.addHeader("Cache-Control","no-cache");
        response.addHeader("X-Accel-Buffering","no");

        String ip = request.getRemoteAddr() + ":" + request.getRemotePort();
        SseEmitter sseEmitter = sseService.errorInfoConnect(ip);
        try {
            sseEmitter.send(SseEmitter.event().name("errorInfo").comment("开始推送机台报警信息："));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return sseEmitter;
    }
}
